<!DOCTYPE html>
<html lang="zh" class="no-js">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="description" content="book">
<meta name="generator" content="Paradox, paradox-material-theme=0.6.0, mkdocs-material=3.0.3">

<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="">
<meta name="lang:search.pipeline.stopwords" content="true">
<meta name="lang:search.pipeline.trimmer" content="true">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">


<meta name="description" content="book">
<link rel="shortcut icon" href="../assets/images/favicon.png">
<title>Route 路由 · Scala Web 开发——基于Akka HTTP</title>
<link rel="stylesheet" href="../assets/stylesheets/application.451f80e5.css">
<link rel="stylesheet" href="../assets/stylesheets/application-palette.22915126.css">
<meta name="theme-color" content="#009688" />
<link rel="stylesheet" href="../lib/material__tabs/dist/mdc.tabs.min.css">
<link rel="stylesheet" href="../lib/prettify/prettify.css">
<script src="../assets/javascripts/modernizr.1aa3b519.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,400i,700|Roboto+Mono">
<style>
body,input{font-family:"Roboto","Helvetica Neue",Helvetica,Arial,sans-serif}
code,kbd,pre{font-family:"Roboto Mono","Courier New",Courier,monospace}
</style>
<link rel="stylesheet" href="../assets/fonts/font-awesome.css">
<link rel="stylesheet" href="../assets/fonts/material-icons.css">
<link rel="stylesheet" href="../assets/stylesheets/paradox-material-theme.css">
</head>
<body
data-md-color-primary="teal"
data-md-color-accent="indigo"
>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer" autocomplete="off">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search" autocomplete="off">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="Scala Web 开发——基于Akka HTTP" class="md-header-nav__button md-logo">
<i class="md-icon">local_library</i>
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">
Scala Web 开发——基于Akka HTTP
</span>
<span class="md-header-nav__topic">
Route 路由
</span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" name="search">
<input type="text" class="md-search__input" name="query" placeholder="Search" autocapitalize="off" autocorrect="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">&#xE5CD;</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>

</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/yangbajing/scala-web-development"
title="Go to repository"
class="md-source"
data-md-source="github">
<div class="md-source__icon">
<i class="fa fa-github"></i>
</div>
<div class="md-source__repository">
yangbajing/scala-web-development
</div>
</a>

</div>
</div>
</div>
</nav>
</header>

<div class="md-container">
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0" style="visibility: hidden">
<label class="md-nav__title md-nav__title--site" for="drawer">
<a href="../index.html" title="Scala Web 开发——基于Akka HTTP" class="md-nav__button md-logo">
<span class="md-nav__button md-logo">
<i class="md-icon">local_library</i>
</a>
<a href="../index.html" title="Scala Web 开发——基于Akka HTTP">
Scala Web 开发——基于Akka HTTP
</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/yangbajing/scala-web-development"
title="Go to repository"
class="md-source"
data-md-source="github">
<div class="md-source__icon">
<i class="fa fa-github"></i>
</div>
<div class="md-source__repository">
yangbajing/scala-web-development
</div>
</a>

</div>
<ul>
  <li><a href="../preface.html" class="page">前言</a></li>
  <li><a href="../env/index.html" class="page">Scala 环境配置</a>
  <ul>
    <li><a href="../env/env.1.html" class="page">Sbt</a></li>
    <li><a href="../env/env.2.html" class="page">IDE开发工具</a></li>
    <li><a href="../env/env.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../scala/index.html" class="page">Scala 语言基础</a>
  <ul>
    <li><a href="../scala/scala.0.html" class="page">REPL</a></li>
    <li><a href="../scala/scala.1.html" class="page">你好，Scala</a></li>
    <li><a href="../scala/scala.2.html" class="page">Scala基础</a></li>
    <li><a href="../scala/scala.3.html" class="page">流程和函数</a></li>
    <li><a href="../scala/scala.4.html" class="page">集合</a></li>
    <li><a href="../scala/scala.5.html" class="page">class和object</a></li>
    <li><a href="../scala/scala.6.html" class="page">函数式</a></li>
    <li><a href="../scala/scala.7.html" class="page">Trait</a></li>
    <li><a href="../scala/scala.8.html" class="page">并发</a></li>
    <li><a href="../scala/scala.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../basic/index.html" class="page">Akka HTTP 基础</a>
  <ul>
    <li><a href="../basic/basic.0.html" class="page">Akka HTTP 基础</a></li>
    <li><a href="../basic/basic.1.html" class="page">Web 工作方式</a></li>
    <li><a href="../basic/basic.2.html" class="page">使用 Akka Http 搭建一个简单的 Web 服务</a></li>
    <li><a href="../basic/basic.3.html" class="page">Akka HTTP 的通用抽象</a></li>
    <li><a href="../basic/basic.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../server-api/index.html" class="page">服务端API</a>
  <ul>
    <li><a href="../server-api/work.html" class="page">Akka HTTP 如何使得 Web 工作</a></li>
    <li><a href="../server-api/advanced.html" class="page">高级服务端 API</a></li>
  </ul></li>
  <li><a href="../routing-dsl/index.html" class="page">路由DSL</a>
  <ul>
    <li><a href="../routing-dsl/route.html" class="active page">Route 路由</a></li>
    <li><a href="../routing-dsl/directive.html" class="page">Directive 指令</a></li>
    <li><a href="../routing-dsl/custom-directive.html" class="page">自定义指令</a></li>
    <li><a href="../routing-dsl/rejections.html" class="page">拒绝 rejections</a></li>
    <li><a href="../routing-dsl/exception.html" class="page">异常处理</a></li>
    <li><a href="../routing-dsl/file-upload.html" class="page">实战：大文件断点上传、下载和秒传</a></li>
  </ul></li>
  <li><a href="../directives/index.html" class="page">常用指令</a>
  <ul>
    <li><a href="../directives/path.html" class="page">PathDirectives（路径指令）</a></li>
    <li><a href="../directives/method.html" class="page">directives/method.html</a></li>
    <li><a href="../directives/parameter_form.html" class="page">directives/parameter_form.html</a></li>
    <li><a href="../directives/marshalling.html" class="page">directives/marshalling.html</a></li>
    <li><a href="../directives/file.html" class="page">directives/file.html</a></li>
    <li><a href="../directives/cookie.html" class="page">directives/cookie.html</a></li>
  </ul></li>
  <li><a href="../data/index.html" class="page">数据</a>
  <ul>
    <li><a href="../data/data.0.html" class="page">数据</a></li>
    <li><a href="../data/data.1.html" class="page">JSON</a></li>
    <li><a href="../data/data.ant-design-pro.html" class="page">实战：为Ant Design Pro提供后端接口</a></li>
    <li><a href="../data/data.kryo.html" class="page">Kryo</a></li>
    <li><a href="../data/data.2.html" class="page">Protobuf</a></li>
    <li><a href="../data/data.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../test/index.html" class="page">测试</a>
  <ul>
    <li><a href="../test/test.0.html" class="page">测试</a></li>
    <li><a href="../test/test.1.html" class="page">Scalatest</a></li>
    <li><a href="../test/test.2.html" class="page">测试异步代码</a></li>
    <li><a href="../test/test.3.html" class="page">端到端测试Route</a></li>
    <li><a href="../test/test.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../actor/index.html" class="page">Akka Actor</a>
  <ul>
    <li><a href="../actor/actor.html" class="page">Akka Typed Actor</a></li>
    <li><a href="../actor/actor-test.html" class="page">Akka Actor 测试</a></li>
    <li><a href="../actor/actor.z.html" class="page">Actor小结</a></li>
  </ul></li>
  <li><a href="../oauth/index.html" class="page">实战：实现OAuth 2服务</a>
  <ul>
    <li><a href="../oauth/oauth.0.html" class="page">实战：OAuth 2 服务</a></li>
    <li><a href="../oauth/oauth.1.html" class="page">OAuth 2简介</a></li>
    <li><a href="../oauth/oauth.2.html" class="page">OAuth 2接口设计</a></li>
    <li><a href="../oauth/oauth.3.html" class="page">OAuth 2服务实现</a></li>
    <li><a href="../oauth/oauth.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../database/index.html" class="page">访问数据库</a>
  <ul>
    <li><a href="../database/database.0.html" class="page">访问数据库</a></li>
    <li><a href="../database/database.1.html" class="page">使用 JDBC 访问 PostgreSQL</a></li>
    <li><a href="../database/database.2.html" class="page">使用 Slick 访问数据库</a></li>
    <li><a href="../database/database.3.html" class="page">访问 Cassandra 数据库</a></li>
    <li><a href="../database/database.4.html" class="page">访问 Redis</a></li>
    <li><a href="../database/database.5.html" class="page">访问 Elasticsearch</a></li>
    <li><a href="../database/database.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../engineering/index.html" class="page">工程化</a>
  <ul>
    <li><a href="../engineering/swagger.html" class="page">使用Swagger编写API文档</a></li>
    <li><a href="../engineering/guice.html" class="page">使用Guice管理类依赖</a></li>
  </ul></li>
  <li><a href="../grpc/index.html" class="page">Akka gRPC</a>
  <ul>
    <li><a href="../grpc/grpc.html" class="page">gRPC服务</a></li>
    <li><a href="../grpc/build-tool.html" class="page">构建工具</a></li>
    <li><a href="../grpc/deployment.html" class="page">部署</a></li>
    <li><a href="../grpc/grpc.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../config-discovery/index.html" class="page">实战：配置管理、服务发现系统</a></li>
  <li><a href="../appendix/index.html" class="page">附录</a>
  <ul>
    <li><a href="../appendix/appendix.0.html" class="page">参考资料</a></li>
    <li><a href="../appendix/appendix.1.html" class="page">专业术语</a></li>
    <li><a href="../appendix/appendix.2.html" class="page">词汇表</a></li>
  </ul></li>
  <li><a href="../donate.html" class="page">赞助</a></li>
</ul>
<nav class="md-nav md-nav--secondary">
<label class="md-nav__title" for="__toc">Table of contents</label>
<ul>
  <li><a href="../routing-dsl/route.html#route-路由" class="header">Route 路由</a>
  <ul>
    <li><a href="../routing-dsl/route.html#requestcontext" class="header">RequestContext</a></li>
    <li><a href="../routing-dsl/route.html#routeresult" class="header">RouteResult</a></li>
    <li><a href="../routing-dsl/route.html#组合路由" class="header">组合路由</a></li>
    <li><a href="../routing-dsl/route.html#路由树" class="header">路由树</a></li>
  </ul></li>
</ul>
</nav>

</nav>
<ul style="display: none">
<li class="md-nav__item md-version" id="project.version">
<label class="md-nav__link" for="__version">
<i class="md-icon" title="Version">label_outline</i> 1.0.0
</label>
</li>
</ul>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<label class="md-nav__title" for="__toc">Table of contents</label>
<ul>
  <li><a href="../routing-dsl/route.html#route-路由" class="header">Route 路由</a>
  <ul>
    <li><a href="../routing-dsl/route.html#requestcontext" class="header">RequestContext</a></li>
    <li><a href="../routing-dsl/route.html#routeresult" class="header">RouteResult</a></li>
    <li><a href="../routing-dsl/route.html#组合路由" class="header">组合路由</a></li>
    <li><a href="../routing-dsl/route.html#路由树" class="header">路由树</a></li>
  </ul></li>
</ul>
</nav>

</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset">
<div class="md-content__searchable">
<h1><a href="#route-路由" name="route-路由" class="anchor"><span class="anchor-link"></span></a>Route 路由</h1>
<pre><code>type Route = RequestContext =&gt; Future[RouteResult]
</code></pre>
<p>Akka HTTP 里路由是类型 <code>Route</code> 只是一个类型别名，它实际上是一个函数 <code>RequestContext =&gt; Future[RouteResult]</code>，它接受一个 <code>RequestContext</code> 参数，并返回 <code>Future[RouteResult]</code>。<code>RequestContext</code>保存了每次HTTP请求的上下文，包括<code>HttpRequest</code>、<code>unmatchedPath</code>、<code>settings</code>等请求资源，还有4个函数来响应数据给客户端：</p>
<ul>
  <li><code>def complete(obj: ToResponseMarshallable): Future[RouteResult]</code>：请求正常完成时调用，返回数据给前端。通过 <strong>Marshal</strong> 的方式将用户响应的数据类型转换成 <code>HttpResponse</code>，再赋值给<code>RouteResult.Complete</code>。</li>
  <li><code>def reject(rejections: Rejection*): Future[RouteResult]</code>：请求不能被处理时调用，如：路径不存、HTTP方法不支持、参数不对、Content-Type不匹配等。也可以自定义<code>Rejection</code>类型。</li>
  <li>
  <p><code>def redirect(uri: Uri, redirectionType: Redirection): Future[RouteResult]</code>：用指定的url地址和给定的HTTP重定向响应状态告知客户端需要重定向的地址和方式。<code>redirect</code>实际上是对<code>complete</code>的封装，可以通过向<code>complete</code>函数传入指定的<code>HttpResponse</code>实例实现：</p>
  <pre class="prettyprint"><code class="language-scala">complete(HttpResponse(
  status = redirectionType,
  headers = headers.Location(uri) :: Nil,
  entity = redirectionType.htmlTemplate match {
    case &quot;&quot;       =&gt; HttpEntity.Empty
    case template =&gt; HttpEntity(ContentTypes.`text/html(UTF-8)`, template format uri)
  }))
</code></pre></li>
  <li><code>def fail(error: Throwable): Future[RouteResult]</code>：将给定异常实例气泡方式向上传递，将由最近的<code>handleExceptions</code>指令和<code>ExceptionHandler</code>句柄处理该异常（若异常类型是<code>RejectionError</code>，将会被包装成<code>Rejection</code>来执行）。</li>
</ul>
<h2><a href="#requestcontext" name="requestcontext" class="anchor"><span class="anchor-link"></span></a>RequestContext</h2>
<p><code>RequestContext</code>包装了HTTP请求的实例<code>HttpRequest</code>和运行时需要的一些上下文信息，如：<code>ExcutionContext</code>、<code>Materializer</code>、<code>LoggingAdapter</code>、<code>RoutingSettings</code>等，还有<code>unmatchedPath</code>，该值描述了请求UIR还未被匹配的路径。</p><div class="callout note "><div class="callout-title">unmatchedPath</div>
<p>若请求URI地址为：<code>/api/user/page</code>，对于如下路由定义<code>unmatchedPath</code>将为 <code>/user/page</code>。</p>
<pre class="prettyprint"><code class="language-scala">  pathPrefix(&quot;api&quot;) { ctx =&gt;
    // ctx.unmatchedPath 等价于 &quot;/user/page&quot;
    ctx.complete(ctx.request.uri.path.toString())
  }
</code></pre></div>
<h2><a href="#routeresult" name="routeresult" class="anchor"><span class="anchor-link"></span></a>RouteResult</h2>
<p><code>RouteResult</code>是一个简单的ADT（抽象数据类型），对路由执行后可能的结果进行建模，定义为：</p>
<pre class="prettyprint"><code class="language-scala">sealed trait RouteResult extends javadsl.server.RouteResult

object RouteResult {
  final case class Complete(response: HttpResponse) extends javadsl.server.Complete with RouteResult {
    override def getResponse = response
  }
  final case class Rejected(rejections: immutable.Seq[Rejection]) extends javadsl.server.Rejected with RouteResult {
    override def getRejections = rejections.map(r =&gt; r: javadsl.server.Rejection).toIterable.asJava
  }
}
</code></pre>
<p>通常不需要我们直接创建<code>RouteResult</code>实例，而是通过预定义的指令<code>RouteDirectives</code>定义的函数（<code>complete</code>、<code>reject</code>、<code>redirect</code>、<code>fail</code>）或<code>RequestContext</code>上的方法来创建。</p>
<h2><a href="#组合路由" name="组合路由" class="anchor"><span class="anchor-link"></span></a>组合路由</h2>
<p>将单个的路由组合成一个复杂的路由结构一般有3种方法：</p>
<ol>
  <li><strong>路由转换（嵌套）</strong>，将请求委托给另一个“内部”路由，在此过程中可以更改传请求和输出结果的某些属性。</li>
  <li><strong>过滤路由</strong>，只允许满足给定条件的路由通过。</li>
  <li><strong>链接路由</strong>，若给定的第一个路由被拒绝（reject），将尝试第二个路由，并依次类推。通过级联操作符<code>~</code>来实现，导入<code>akka.http.scaladsl.server.Directvies._</code>后可用。</li>
</ol>
<p>前两种方法可由指令（Directive）提供，Akka HTTP已经预告定义了大量开箱即用的指令，也可以自定义我们自己的指令。通过指令这样的机制，使得Akka HTTP的路由定义异常强大和灵活。</p>
<h2><a href="#路由树" name="路由树" class="anchor"><span class="anchor-link"></span></a>路由树</h2>
<p>当通过嵌套和链接将指令和自定义路由组合起来构建成一个路由结构时，将形成一颗树。当一个HTTP请求进入时，它首先被注入的树的根，并以深入优先的方式向下流径所有分支，直到某个节点完成它（返回<code>Future[RouteResult.Complete]</code>）或者完全拒绝它（返回<code>Future[RouteResult.Rejected]</code>）。这种机制可以使复杂的路由匹配逻辑可以非常容易的实现：简单地将最特定的情况放在前面，而将一般的情况放在后面。</p>
<pre class="prettyprint"><code class="language-scala">val route =
  a {
    b {
      c {
        ... // route 1
      } ~
      d {
        ... // route 2
      } ~
      ... // route 3
    } ~
    e {
      ... // route 4
    }
  }
</code></pre>
<p>上面这个例子：</p>
<ul>
  <li><strong>route 1</strong> 只有当a、b、c都通过时才会到达。</li>
  <li><strong>route 2</strong> 只有当a、b通过，但c被拒绝时才会到达。</li>
  <li><strong>route 3</strong> 只有当a、b通过，但c、d和它之前的所有链接的路由都被拒绝时才会到达。
    <ul>
      <li><em>可以被看作一个捕获所有（catch-all）的默认路由，之后会看到我们将利用此特性来实现服务端对SPA前端应用的支持。</em></li>
    </ul>
  </li>
  <li><strong>route 4</strong> 只有当a通过，b和其所有子节点都被拒绝时才会到达。</li>
</ul>
</div>
<div>
<a href="https://github.com/yangbajing/scala-web-development/tree/master/book/src/main/paradox/routing-dsl/route.md" title="Edit this page" class="md-source-file md-edit">
Edit this page
</a>
</div>
<div class="print-only">
<span class="md-source-file md-version">
1.0.0
</span>
</div>
</article>
</div>
</div>
</main>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="../routing-dsl/index.html" title="路由DSL" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span class="md-footer-nav__direction">
Previous
</span>
路由DSL
</span>
</div>
</a>
<a href="../routing-dsl/directive.html" title="Directive 指令" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span class="md-footer-nav__direction">
Next
</span>
Directive 指令
</span>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
Powered by
<a href="https://github.com/lightbend/paradox">Paradox</a>
and
<a href="https://jonas.github.io/paradox-material-theme/">Paradox Material Theme</a>

</div>
<div class="md-footer-social">
<a href="https://github.com/yangbajing" class="md-footer-social__link fa fa-github"></a><a href="https://weibo.com/yangbajing" class="md-footer-social__link fa fa-globe"></a><a href="https://www.yangbajing.me/" class="md-footer-social__link fa fa-globe"></a>
</div>

</div>
</div>
</footer>

</div>
<script src="../assets/javascripts/application.583bbe55.js"></script>
<script src="../assets/javascripts/paradox-material-theme.js"></script>
<script>app.initialize({version:"0.17",url:{base:"../."}})</script>
<script type="text/javascript" src="../lib/prettify/prettify.js"></script>
<script type="text/javascript" src="../lib/prettify/lang-scala.js"></script>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
window.prettyPrint && prettyPrint();
});
</script>
</body>
</html>
